<template>
  <div class="duty-select-wrapper">
    <el-select
      v-model="selectedValue"
      clearable
      :disabled="props.disabled"
      multiple
      :placeholder="props.placeholder || '请选择职务'"
      @change="handleChange"
      @visible-change="handleVisibleChange"
    >
      <el-option v-for="item in dutyList" :key="item.id" :label="item.name" :value="item.id" />
    </el-select>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import Public from '~/src/api/public'

interface DutyItem {
  id: number
  name: string
}

interface DutyResponse {
  code: number
  result: DutyItem[]
}

const props = defineProps<{
  modelValue: any
  disabled?: boolean
  placeholder?: string
  api?: string
  params?: Record<string, any>
  format?: (value: any) => any[]
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: any): void
  (e: 'change', value: any): void
}>()

const selectedValue = ref<number[]>([])
const dutyList = ref<DutyItem[]>([])
const loading = ref(false)
const isDataLoaded = ref(false)

const processValue = (value: any): number[] => {
  console.log('processValue input:', value)
  if (!value) return []

  if (props.format) {
    const formatted = props.format(value)
    console.log('format result:', formatted)
    return formatted
  }

  if (Array.isArray(value)) {
    const result = value
      .map((item: any) => {
        if (typeof item === 'object') {
          if (item.posts) {
            return Number(item.posts.id)
          }
          if (item.postsId) {
            return Number(item.postsId)
          }
          if (item.id) {
            return Number(item.id)
          }
        }
        return Number(item)
      })
      .filter(Boolean)
    console.log('array process result:', result)
    return result
  }

  if (typeof value === 'string') {
    const result = value.split(',').map(Number).filter(Boolean)
    console.log('string process result:', result)
    return result
  }

  return []
}

const loadData = async () => {
  if (isDataLoaded.value) return

  try {
    loading.value = true
    const api = props.api || '/api/posts/all'
    const params = props.params || {}
    const res = (await Public.getDropDownListApi({ url: api, ...params })) as unknown as DutyResponse
    console.log('res', res)
    if (res.code === 0) {
      dutyList.value = res.result
      isDataLoaded.value = true
      // 数据加载完成后，重新处理选中值
      const processed = processValue(props.modelValue)
      console.log('after loadData, setting selectedValue:', processed)
      selectedValue.value = processed
    }
  } catch (error) {
    console.error('Failed to load duty data:', error)
  } finally {
    loading.value = false
  }
}

const handleChange = (value: number[]) => {
  console.log('handleChange:', value)
  selectedValue.value = value
  emit('update:modelValue', value)
  emit('change', value)
}

const handleVisibleChange = (visible: boolean) => {
  console.log('handleVisibleChange:', visible)
  if (visible && !isDataLoaded.value) {
    loadData()
  }
}

// 监听 modelValue 的变化
watch(
  () => props.modelValue,
  async (newValue) => {
    console.log('watch triggered, newValue:', newValue)

    // 如果数据未加载，先加载数据
    if (!isDataLoaded.value) {
      console.log('loading data first...')
      await loadData()
    }

    // 确保数据已加载后再处理值
    if (isDataLoaded.value) {
      console.log('processing value after data loaded')
      const processed = processValue(newValue)
      console.log('processed value:', processed)
      selectedValue.value = processed
    }
  },
  { immediate: true, deep: true }
)

// 添加 onMounted 钩子确保初始化
onMounted(async () => {
  console.log('component mounted, loading data...')
  if (!isDataLoaded.value) {
    await loadData()
  }
})

defineExpose({
  selectedValue,
  dutyList,
  loadData,
})
</script>

<style scoped>
.duty-select-wrapper {
  width: 100%;
  display: flex;
}

.el-select {
  width: 100%;
}
</style>
